/*
  普通用户信息相关接口
*/
const express = require('express')
const router = express.Router()
const utils = require('utility')
const path = require('path')
const db = require(path.join(__dirname, '../common/db.js'))
var multer = require('multer')
var upload = multer({
    dest: 'uploads/'
}); // 设置上传目录，得到upload对象
// 路由配置

// 重置密码
router.put('/users/:id', async (req, res) => {
    let param = req.params
    let password = utils.md5(req.body.password)
    let sql = 'update myuser set password = ? where id = ?'
    let ret = await db.operateData(sql, [password, param.id])
    if (ret && ret.affectedRows > 0) {
        res.json({
            status: 0,
            message: '重置密码成功！'
        })
    } else {
        res.json({
            status: 1,
            message: '重置密码失败！'
        })
    }
})

// 更新用户信息
router.put('/upMyuser', upload.array('upload', 1), async (req, res) => {
    // 获取请求参数
    let param = req.body
    console.log(req.files);
    let data = {}
    if (req.files.length === 0) {
        data = {
            // 增加更新用户头像
            user_pic: param.avatar,
            nickname: param.nickname,
            email: param.email
        }
    }
    if (req.files.length !== 0) {
        data = {
            // 增加更新用户头像
            user_pic: param.avatar,
            nickname: param.nickname,
            email: param.email,
            cover_img: req.files[0].filename
        }
    }

    // 更新用户的信息
    let sql = 'update myuser set ? where id = ?'
    // 如果是增删改操作，那么返回对象；如果是查询，那么返回数组
    let ret = await db.operateData(sql, [data, param.id, ])
    // 处理响应状态
    if (ret && ret.affectedRows > 0) {
        res.json({
            status: 0,
            message: '修改用户信息成功！'
        })
    } else {
        res.json({
            status: 1,
            message: '修改用户信息失败！'
        })
    }
})


module.exports = router